﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SnapLib;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Configuration;
using System.Xml;
using TKageyu.Utils;
using System.Runtime.InteropServices;

namespace KeyboardRemapper
{

   public partial class frmAppMenu : Form
   {
      public static void ShowMenu(AppList appList)
      {
         frmAppMenu form = new frmAppMenu(appList);
         form.Show();
      }

      const int ITEM_HEIGHT = 60;
      const int BORDER_WIDTH = 4;
      const int TEXT_POSITION = 70;
      const int ICON_SIZE = 48;
      AppList m_appList;
      System.Windows.Forms.Timer m_tmrCheckForeground;
      private frmAppMenu(AppList appList)
      {
         m_appList = appList;
         InitializeComponent();
         Height = m_appList.Count * ITEM_HEIGHT + BORDER_WIDTH * 2;
         Width = 400;
         ShowInTaskbar = false;
         int pos = BORDER_WIDTH;
         foreach (AppInfo app in m_appList)
         {
            TaskButton btn = new TaskButton(app);
            btn.Top = pos;
            btn.Width = Width;
            btn.Height = ITEM_HEIGHT;
            btn.Parent = this;
            btn.Font = Font;
            btn.Click += new EventHandler(btn_Click);
            pos += ITEM_HEIGHT;
         }
         TopMost = true;

         foreach (Screen s in Screen.AllScreens)
         {
            if (s.Bounds.Contains(Cursor.Position))
            {
               Left = s.Bounds.Left + (s.WorkingArea.Width - Width) / 2;
               Top = s.Bounds.Top + (s.WorkingArea.Height - Height) / 2;
            }
         }
         this.Shown += new EventHandler(frmAppMenu_Shown);
         m_tmrCheckForeground = new System.Windows.Forms.Timer();
         m_tmrCheckForeground.Interval = 100;
         m_tmrCheckForeground.Tick += new EventHandler(m_tmrCheckForeground_Tick);
         
      }

      int timeout = 0;
      void m_tmrCheckForeground_Tick(object sender, EventArgs e)
      {
         if (ForeignWindow.ForegroundWindow != new ForeignWindow(this.Handle))
         {
            timeout++;
            if (timeout > 10)
               Close();
         }
         else
            timeout = 0;
      }

      void frmAppMenu_Shown(object sender, EventArgs e)
      {
         Activate();
         Focus();
         m_tmrCheckForeground.Start();
      }

      void btn_Click(object sender, EventArgs e)
      {
         Hide();
      }

      private void ShowMenu()
      {

      }

      public class TaskButton : Button
      {
         public AppInfo m_app;
         Font m_shortcutFont;
         public TaskButton(AppInfo app)
         {
            m_app = app;
            m_shortcutFont = new Font(Font.Name, 7, Font.Style);
         }

         protected override void OnPaint(PaintEventArgs pevent)
         {
            base.OnPaint(pevent);
            Rectangle drawArea = pevent.ClipRectangle;
            drawArea.Inflate(-5, -5);
            Rectangle textArea = new Rectangle(drawArea.Left + TEXT_POSITION, drawArea.Top, drawArea.Width - TEXT_POSITION, drawArea.Height);
            Rectangle iconArea = new Rectangle(drawArea.Left + (TEXT_POSITION - ICON_SIZE) / 2,
               drawArea.Top + (drawArea.Height - ICON_SIZE) / 2
               , ICON_SIZE, ICON_SIZE);
            using (SolidBrush b = new SolidBrush(SystemColors.ButtonFace))
               pevent.Graphics.FillRectangle(b, drawArea);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            pevent.Graphics.DrawString(m_app.pDisplayName, Font, Brushes.Black, textArea, sf);

            Rectangle textAreaShortCut = new Rectangle(drawArea.Left + TEXT_POSITION, drawArea.Top, drawArea.Width - TEXT_POSITION, drawArea.Height);
            textAreaShortCut.Offset(0, 5 + ((int)(pevent.Graphics.MeasureString("Cg", Font).Height / 2)));

            if (m_app.Icon != null)
            {
               pevent.Graphics.DrawIcon(m_app.Icon, iconArea);
            }
         }

         protected override void OnClick(EventArgs e)
         {
            base.OnClick(e);
            Run();
         }

         public void Run()
         {
            bool bFound = false;
            foreach (ForeignWindow w in ForeignWindow.TopMostWindows)
            {
               if (!string.IsNullOrEmpty(m_app.pCaptionContains) && w.Caption.Contains(m_app.pCaptionContains))
               {
                  if (w.WindowState != WindowShowStyle.ShowMaximized)
                     w.Show(WindowShowStyle.Restore);
                  else
                     w.Show(WindowShowStyle.ShowMaximized);
                  w.BringToFront();
                  Thread.Sleep(100);
                  w.Activate();
                  w.Show(WindowShowStyle.Show);
                  bFound = true;
                  break;
               }
            }
            if (!bFound && m_app.pExePath != null)
            {
               Process.Start(m_app.pExePath);
            }
         }
      }

      public class AppList : List<AppInfo>
      {
      }
      public class AppInfo
      {
         public string pExePath { get; set; }
         public string pParameters { get; set; }
         public string pCaptionContains { get; set; }
         public string pDisplayName { get; set; }
         public int pIconIndex { get; set; }

         public AppInfo(string sLine)
         {
            string[] parts = sLine.Split(',');
            pDisplayName = parts[0];
            pExePath = parts[1];
            pIconIndex = parts[2].ToInt(0);
            pParameters = parts[3];
            pCaptionContains = parts[4];
         }

         public override string ToString()
         {
            return pDisplayName;
         }

         public string Serialize()
         {
            return pDisplayName + "," + pExePath + "," + pIconIndex + "," + pParameters + "," + pCaptionContains;
         }


         public Icon Icon
         {
            get
            {
               if (m_icon == null)
               {
                  if (pExePath != null)
                  {
                     try
                     {
                        IconExtractor ic = new IconExtractor(pExePath);
                        m_icon = ic.GetIcon(pIconIndex);
                        ic.Dispose();
                     }
                     catch
                     {
                        m_icon = Icon.ExtractAssociatedIcon(pExePath);
                     }
                  }
               }
               return m_icon;
            }
         }

         private Icon m_icon = null;
      }


      private void Form1_Deactivate(object sender, EventArgs e)
      {
         Close();
      }

      private void frmAppMenu_FormClosing(object sender, FormClosingEventArgs e)
      {
         m_tmrCheckForeground.Stop();
         m_tmrCheckForeground.Dispose();
      }



   }

}
